package de.arndt_panzer.bensgallery;

import java.util.ArrayList;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class StatusBroadcastService extends Service {
	
	final static String				TAG			= StatusBroadcastService.class.getSimpleName();
	final static ArrayList<Handler>	CALLBACKS	= new ArrayList<Handler>();
	final StatusBroadcastReceiver	mReceiver	= new StatusBroadcastReceiver();
	
	public final static void addReceiver(Handler callback) {
		synchronized (CALLBACKS) {
			CALLBACKS.remove(callback);
			CALLBACKS.add(callback);
		}
	}
	
	public final static void removeReceiver(Handler callback) {
		synchronized (CALLBACKS) {
			CALLBACKS.remove(callback);
		}
	}
	
	private class StatusBroadcastReceiver extends BroadcastReceiver {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction() == null) return;
			if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
				Intent i = new Intent(context, MainActivity.class);
				i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(i);
			}
			
			// send to all registered receiver
			ArrayList<Handler> remove = new ArrayList<Handler>();
			synchronized (CALLBACKS) {
				for (Handler handler : CALLBACKS) {
					try {
						Message msg = new Message();
						Bundle data = new Bundle();
						data.putString("action", intent.getAction());
						msg.setData(data);
						if (!handler.sendMessage(msg)) {
							remove.add(handler);
							Log.d(	TAG,
									"onReceive(): Failed send message " + intent.getAction());
						}
					} catch (Exception e) {
						remove.add(handler);
					}
				}
				CALLBACKS.removeAll(remove);
			}
			
		}
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		filter.addAction(Intent.ACTION_SCREEN_ON);
		filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		filter.addAction(Intent.ACTION_BOOT_COMPLETED);
		this.registerReceiver(mReceiver, filter);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		this.unregisterReceiver(mReceiver);
	}
	
}
